package com.example.steam520.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//@EnableMethodSecurity(securedEnabled = true) // 启用基于注解的方法级安全控制
public class WebSecurityConfig {

    // 注释掉内存用户配置
    // @Bean
    // public UserDetailsService userDetailsService() {
    //     InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
    //     users.createUser(User.withUsername("zhangsan")
    //             .password("{noop}1234")
    //             .roles("ADMIN")
    //             .build());
    //     return users;
    // }

    // 创建密码编码器，用于对用户密码进行加密存储
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//BCrypt加密
    }

    // 3. 配置Security过滤器链（基础认证逻辑）
//    @Bean
//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
//                .formLogin(AbstractAuthenticationFilterConfigurer::permitAll)
//                .logout(LogoutConfigurer::permitAll)
//                .csrf(AbstractHttpConfigurer::disable);
//        return http.build();
//    }
    @Bean// 4. Web授权配置
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // 1. URL权限控制
        http.authorizeHttpRequests(auth -> auth
                        // 放行登录页、静态资源
                        .requestMatchers("/loginview", "/css/**", "/img/**", "/js/**").permitAll()
                        // ADMIN角色可访问图书管理页
//                        .requestMatchers("/book/admin/**").hasRole("ADMIN")//注释掉，使用方法授权
                        // 其他请求都需要登录
                        .anyRequest().authenticated()
                )
                // 2. 自定义表单登录
                .formLogin(form -> form
                        .loginPage("/loginview") // 自定义登录页（login.html）
                        .loginProcessingUrl("/doLogin") // 登录请求处理地址
                        .defaultSuccessUrl("/book/main", true) // 登录成功跳转页
                        .permitAll()
                )
                // 3. 注销配置
                .logout(LogoutConfigurer::permitAll)
                // 4. 适配同源frame页面
                .csrf(AbstractHttpConfigurer::disable)
                .headers(headers -> headers
                        .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
                );
        return http.build();
    }
}
